<script setup>
import { RouterView, useRouter, useRoute } from "vue-router";
import AiPhotoReady from "@/components/AiPhotoReady.vue";
import { ref, onMounted, onUnmounted, nextTick, watch, provide } from "vue";
import { ClientJS } from "clientjs"; // 引入 ClientJS
import CryptoJS from "crypto-js"; // 安装 crypto-js

import { trackEvent } from "@/utils/firebase";
import { useAuthStore } from "@/stores/authStore";
import LoginDailog from "@/components/LoginDailog.vue";
import api from "@/api";
import { usePollingStore } from "@/stores/polling";
import axios from "axios";

const store = usePollingStore();
const authStore = useAuthStore();
const router = useRouter();
const route = useRoute();

const showPopup = ref(false);
const imgUrl = ref("");
const taskType = ref(0);
const taskNo = ref("");

// 监听最新完成的任务
watch(
  () => store.latestCompletedTask,
  (newTask) => {
    if (newTask && newTask.imgUrl) {
      imgUrl.value = newTask.imgUrl;
      taskType.value = newTask.taskType;
      taskNo.value = newTask.taskNo;
      // 检查当前路由是否需要显示弹窗
      if (shouldShowPopup()) {
        showPopup.value = true;
        // 60秒后自动关闭
        setTimeout(() => {
          showPopup.value = false;
          // 清除最新任务记录
          store.clearLatestCompletedTask();
        }, 60000);
      }
    }
  }
);

// 判断是否应该显示弹窗
const shouldShowPopup = () => {
  const currentPath = route.path;
  return !["/removeCreating", "/poseCreating"].includes(currentPath);
};

// 手动关闭弹窗时清除任务记录
const handleClosePopup = () => {
  showPopup.value = false;
  store.clearLatestCompletedTask();
};

//------------- 气泡逻辑 start-----------------
const showBubble = ref(false);
const offset = ref({ x: 0, y: 0 });
const floatingBubbleRef = ref(null);

const getBubbleDom = () => floatingBubbleRef.value?.$el;

// 计算位置
const calculateOffset = () => {
  const dom = getBubbleDom();
  if (!dom) return;
  const bubbleWidth = Number(dom.offsetWidth) || 0;
  const bubbleHeight = Number(dom.offsetHeight) || 0;

  // 目标位置：right=100px, bottom=160px
  const designRightMargin = 100; // 右侧间距
  const designBottomMargin = 160; // 底部间距

  // 动态计算偏移量
  const x = document.documentElement.clientWidth - designRightMargin - bubbleWidth;
  const y = document.documentElement.clientHeight - designBottomMargin - bubbleHeight;

  offset.value = { x: x, y: y };
};

//------------- 气泡逻辑 end-----------------

const showKeepBack = () => {
  router.push('/keepBack');
  trackEvent("点击_折扣浮窗", { id: "100014" });
};

// 从接口获取的毫秒数
const timeMs = ref(30000); // 默认30秒
// 倒计时
const queryOrderTime = async () => {

  try {
    const res = await api.orderCountdown();
    if (res.data?.remainingSeconds) {
      //如果剩余时间不是0，就显示气泡弹框
      if (!showBubble.value) {
        //如果弹框已经在显示，就不上报
        trackEvent("展示_折扣浮窗", { id: "100013" });
      }
      showBubble.value = true;
      timeMs.value = res.data.remainingSeconds * 1000;
      // 渲染出弹框，再计算位置
      nextTick(() => {
        calculateOffset();
      });
    }
  } catch (err) {
    console.log(err);
  }
};

// 新增：提供queryOrderTime方法
provide("queryOrderTime", queryOrderTime); // 将方法暴露给子组件
provide("show", showPopup);
// 倒计时结束 handleCountdownFinish
const handleCountdownFinish = () => {
  showBubble.value = false;
};

// 创建配置好的 Axios 实例（仅在 App.vue 中使用）
const newApi = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // 使用环境变量
  timeout: 10000, // 10秒超时
  headers: {
    "Content-Type": "application/json",
  },
});

// 确保 device_fingerprint 初始化完成
const initDeviceFingerprint = async () => {
  const device_fingerprint = localStorage.getItem("device_fingerprint");
  if (!device_fingerprint) {
    const client = new ClientJS(); // 创建实例
    const baseFingerprint = client.getFingerprint(); // 获取指纹，这一步得到的是 十六进制字符串，如：55714105
    const fingerprint = CryptoJS.MD5(String(baseFingerprint)).toString(); // 转换为 32 位十六进制字符串（hash）
    // 请求隐藏登录
    try {
      const res = await newApi.post("/api/v1/user/guest/login", {
        deviceId: baseFingerprint,
      });
      if (res.data.data?.token) {
        // 更新状态
        authStore.isrealLogin = false; //游客静默登录；
        authStore.user = res.data.data.name;
        authStore.token = res.data.data.token;
        authStore.eventType = res.data.data.eventType;
        authStore.lastLogin = new Date().toISOString();
        // 持久化存储
        localStorage.setItem("token", res.data.data.token);
      }
      localStorage.setItem("device_fingerprint", fingerprint);
      localStorage.setItem("baseFingerprint", baseFingerprint);
    } catch (error) {
      console.error("请求失败:", error);
      // 存储指纹
      localStorage.setItem("device_fingerprint", fingerprint);
      localStorage.setItem("baseFingerprint", baseFingerprint);
    }
    return device_fingerprint;
  }
};

// 监听路由变化
const stopWatch = watch(
  () => router.currentRoute.value,
  async () => {
    await queryOrderTime(); // 路由切换时调用
  }
);

onMounted(async () => {
  // 获取归因参数
  const params = new URLSearchParams(window.location.search);
  const click_id = params.get("click_id") || "";
  const vid = params.get("vid") || "";
  if (click_id) {
    localStorage.setItem("click_id", click_id);
  }
  if (vid) {
    localStorage.setItem("vid", vid);
  }

  await initDeviceFingerprint(); // 确保指纹初始化完成
  //await queryOrderTime(); // 延迟调用
  // 获取浏览器指纹
  let fingerId = localStorage.getItem("baseFingerprint")
    ? localStorage.getItem("baseFingerprint")
    : "";
  // 计算控制气泡位置
  await nextTick(calculateOffset);
  window.addEventListener("resize", calculateOffset);

  // 埋点：活跃用户 （用户进入页面打一次之后每隔10分钟用户如果有刷新或者重新进入页面再打一次，用户处于登录状态带上udid）
  trackEvent("活跃用户", { id: "10000" });

  // 用户获取到归因信息的时候上报点位
  trackEvent("归因成功", { id: "100001" });
  trackEvent("用户创建游客账号成功", { id: "100002", udid: fingerId });
});

onUnmounted(() => {
  window.removeEventListener("resize", calculateOffset);
  stopWatch(); // 组件卸载时停止监听
});
</script>

<template>
  <RouterView />
  <AiPhotoReady :show="showPopup" :taskType="taskType" :taskNo="taskNo" :imgUrl="imgUrl" @close="handleClosePopup" />
  <!-- 登录弹窗 -->
  <LoginDailog v-show="authStore.isLoginDialogVisible" @close="authStore.hideLoginDialog" />
  <!-- 未支付气泡显示 -->
  <van-floating-bubble ref="floatingBubbleRef" v-model:offset="offset" v-if="showBubble" axis="xy" :gap="0">
    <div class="img_wrap" @click="showKeepBack">
      <img src="@/assets/images/pic_safe@2x.png" />
      <span class="pecent_num">50%</span>
      <span class="off_text">OFF</span>
      <van-count-down :time="timeMs" format="mm:ss" class="time_text" @finish="handleCountdownFinish" />
    </div>
  </van-floating-bubble>
  <!-- 挽留弹框 -->

</template>

<style lang="less">
.van-floating-bubble {
  width: 88px !important;
  height: 112px !important;
  background: none !important;

  .img_wrap {
    width: 100%;
    height: 100%;
    position: relative;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .pecent_num {
      position: absolute;
      left: 8px;
      bottom: 18px;
      font-size: 20px;
      color: #fff;
      font-weight: bold;
    }

    .off_text {
      position: absolute;
      right: 6px;
      bottom: 22px;
      font-size: 13px;
      color: #fff;
      font-weight: bold;
    }

    .time_text {
      position: absolute;
      left: 29px;
      bottom: 4px;
      font-size: 10px;
      color: #fff;
      font-weight: bold;
    }
  }
}
</style>
